package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"goapi/entity"
	"goapi/service"
	encode "goapi/utils/encode"
	"goapi/utils/jwt"
	"goapi/utils/result"
	"net/http"
)

type RespData struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Token    string `json:"token"`
}

func Login(c *gin.Context) {
	var manager entity.Manager
	if err := c.BindJSON(&manager); err != nil {
		c.JSON(http.StatusOK, result.Error(401, "参数错误", nil))
		c.Abort()
		return
	}
	info, err := service.Manager{}.SelectManagerInfoByAccount(manager.Account)
	if err != nil {
		c.JSON(http.StatusOK, result.Error(401, "登录错误", err))
		c.Abort()
		return
	}

	if info.Password != encode.GeneratorMD5(manager.Password) {
		c.JSON(http.StatusOK, result.Error(400, "密码错误", err))
		c.Abort()
		return
	}

	token, err := jwt.GenerateToken(info.UserName, info.Password)
	if err != nil {
		c.JSON(http.StatusOK, result.Error(401, "Token错误", err))
		c.Abort()
		return
	}

	respData := RespData{Username: info.UserName, Password: info.Password, Token: token}

	fmt.Println(info)
	c.JSON(http.StatusOK, result.Success(respData))
}
